package com.doubao.device.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.doubao.common.result.Result;
import com.doubao.device.entity.SmartDevice;
import com.doubao.device.mapper.SmartDeviceMapper;
import com.doubao.device.service.AccessControlService;
import com.doubao.user.entity.MembershipOperationLog;
import com.doubao.user.entity.UserMembership;
import com.doubao.user.mapper.MembershipOperationLogMapper;
import com.doubao.user.mapper.UserMembershipMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDateTime;

/**
 * 访问控制服务实现类
 */
@Service
@Slf4j
public class AccessControlServiceImpl implements AccessControlService {

    private final SmartDeviceMapper smartDeviceMapper;
    private final UserMembershipMapper userMembershipMapper;
    private final MembershipOperationLogMapper operationLogMapper;

    @Autowired
    public AccessControlServiceImpl(
            SmartDeviceMapper smartDeviceMapper,
            UserMembershipMapper userMembershipMapper,
            MembershipOperationLogMapper operationLogMapper) {
        this.smartDeviceMapper = smartDeviceMapper;
        this.userMembershipMapper = userMembershipMapper;
        this.operationLogMapper = operationLogMapper;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<Void> checkDeviceAccess(Long userId, Long deviceId) {
        if (userId == null || deviceId == null) {
            return Result.failed("参数错误");
        }

        // 1. 直接查询智能体信息
        SmartDevice device = smartDeviceMapper.selectById(deviceId);
        if (device == null) {
            return Result.failed("智能体不存在");
        }

        // 2. 如果是普通智能体，直接允许访问
        if (device.getIsPremium() == null || device.getIsPremium() == 0) {
            return Result.success();
        }

        // 3. 如果是会员智能体，检查用户的会员状态
        LambdaQueryWrapper<UserMembership> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserMembership::getUserId, userId)
                .eq(UserMembership::getStatus, 1)
                .ge(UserMembership::getExpireTime, LocalDateTime.now())
                .orderByDesc(UserMembership::getExpireTime)
                .last("LIMIT 1");

        UserMembership membership = userMembershipMapper.selectOne(wrapper);
        if (membership == null) {
            return Result.failed("该智能体需要会员才能使用，请先开通会员");
        }

        // 4. 判断会员是否还有剩余的切换次数
        if (membership.getRemainingSwitchCount() <= 0) {
            return Result.failed("今日切换智能体次数已用完");
        }

        // 5. 更新会员的剩余切换次数
        membership.setRemainingSwitchCount(membership.getRemainingSwitchCount() - 1);
        membership.setUpdatedAt(LocalDateTime.now());
        userMembershipMapper.updateById(membership);

        // 6. 记录操作日志
        MembershipOperationLog log = new MembershipOperationLog();
        log.setUserId(userId);
        log.setMembershipId(membership.getId());
        log.setOperationType("CONSUME");
        log.setLevelId(membership.getLevelId());
        log.setDescription("消费切换智能体次数");
        log.setOldValue(String.valueOf(membership.getRemainingSwitchCount() + 1));
        log.setNewValue(String.valueOf(membership.getRemainingSwitchCount()));
        log.setCreatedAt(LocalDateTime.now());
        operationLogMapper.insert(log);

        // 7. 记录智能体切换操作
        MembershipOperationLog switchLog = new MembershipOperationLog();
        switchLog.setUserId(userId);
        switchLog.setOperationType("SWITCH_AGENT");
        switchLog.setDescription("切换智能体: " + device.getName());
        switchLog.setNewValue("deviceId:" + deviceId);
        switchLog.setCreatedAt(LocalDateTime.now());
        operationLogMapper.insert(switchLog);

        return Result.success();
    }

    /**
     * 检查用户是否是会员
     * @param userId 用户ID
     * @return 是否是会员
     */
    public boolean isVipMember(Long userId) {
        if (userId == null) {
            return false;
        }

        LambdaQueryWrapper<UserMembership> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserMembership::getUserId, userId)
                .eq(UserMembership::getStatus, 1)
                .ge(UserMembership::getExpireTime, LocalDateTime.now())
                .orderByDesc(UserMembership::getExpireTime)
                .last("LIMIT 1");

        UserMembership membership = userMembershipMapper.selectOne(wrapper);
        return membership != null;
    }

    /**
     * 检查用户切换智能体次数是否充足
     * @param userId 用户ID
     * @return 结果
     */
    public boolean hasSufficientSwitchCount(Long userId) {
        if (userId == null) {
            return false;
        }

        // 获取用户会员信息
        LambdaQueryWrapper<UserMembership> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserMembership::getUserId, userId)
                .eq(UserMembership::getStatus, 1)
                .ge(UserMembership::getExpireTime, LocalDateTime.now())
                .orderByDesc(UserMembership::getExpireTime)
                .last("LIMIT 1");

        UserMembership membership = userMembershipMapper.selectOne(wrapper);
        if (membership == null) {
            // 非会员返回false
            return false;
        }

        // 检查会员剩余切换次数
        return membership.getRemainingSwitchCount() > 0;
    }
}